package cn.itcast.web.controller.company;

import cn.itcast.domain.compony.Company;
import cn.itcast.service.company.CompanyService;
import cn.itcast.utils.PageResult;
import cn.itcast.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("company")
public class CompanyController extends BaseController{
    @Autowired
    CompanyService companyService;

    //传统分页
    /*
    @RequestMapping(value="list",name="查询所有的企业")
    public String findAll(
            @RequestParam(defaultValue ="1") int page,
            @RequestParam(defaultValue ="5") int size){
        *//*List<Company> list = companyService.findAll();
        request.setAttribute("list",list);*//*

        //- 接受page(当前页)和size(每页显示的条数),若每页传值的话需要使用默认值.
        //- 调用service中findByPage(page,size)传递过去,返回值PageResult
        PageResult pageResult = companyService.findByPage(page,size);
        //- 将PageResult放入request域中,转发到 company/company-list
        request.setAttribute("page",pageResult);
        return "company/company-list";
    }
*/

    @RequestMapping(value="list",name="查询所有的企业")
    public String findAll(
            @RequestParam(defaultValue ="1") int page,
            @RequestParam(defaultValue ="5") int size){

        //调用service.findByPage(page,size),返回值pageInfo
        PageInfo pageInfo = companyService.findByPage(page, size);

        //将pageInfo放入request域中即可
        request.setAttribute("page",pageInfo);

        return "company/company-list";
    }



    @RequestMapping(value = "toAdd",name="跳转到新增企业页面")
    public String toAdd(){
        return "company/company-add";
    }

    @RequestMapping(value = "edit",name="新增或更新企业")
    public String edit(Company company){
        //根据id有无值,做新增或者更新操作
        if (StringUtils.isBlank(company.getId())) {
            companyService.save(company);
        }else {
            companyService.update(company);
        }
        return "redirect:/company/list.do";
    }


    @RequestMapping(value = "toUpdate",name="跳转到更新企业页面")
    public String toUpdate(String id){
        //根据id查询企业的信息,将这些信息放入域中,在update页面回显
        Company company = companyService.findById(id);
        request.setAttribute("company",company);
        return "company/company-update";
    }


    @RequestMapping(value = "delete",name="删除企业")
    public String deleteById(String id){
        companyService.deleteById(id);
        return "redirect:/company/list.do";
    }

}
